import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:music_app/api/real_api.dart';
import 'package:music_app/controllers/audio_player_controller.dart';
import 'package:music_app/widget/list_song_item.dart';
import 'package:music_app/widget/my_cached_network_image.dart';
import 'package:music_app/widget/play_list_info_detail.dart';

class PlayListView extends StatefulWidget {
  const PlayListView({super.key});

  @override
  State<PlayListView> createState() => _PlayListViewState();
}

class _PlayListViewState extends State<PlayListView> {
  final ScrollController _scrollController = ScrollController();
  final double _headerHeight = 250;
  bool _showTitle = false;
  Map<String, dynamic> _info = {};

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollController.addListener(_onScroll);
      getData();
    });
  }

  Future<void> getData() async {
    try {
      // 获取参数
      final args = Get.arguments as Map<String, dynamic>;
      final id = args['id'] ?? '98317854';
      final response = await RealApi.getPlayListDetail(id);
      final Map<String, dynamic> info = {
        'name': response['playlist']['name'],
        'nickname': response['playlist']['creator']['nickname'],
        'coverImgUrl': response['playlist']['coverImgUrl'],
        'tags': response['playlist']['tags'],
        'description': response['playlist']['description'],
        'songlist': response['playlist']['tracks'],
        'avatarUrl': response['playlist']['creator']['avatarUrl'],
      };
      setState(() {
        _info = info;
      });
    } catch (e) {
      setState(() {
        _info = {};
      });
    } finally {}
  }

  void _onScroll() {
    if (_scrollController.offset > _headerHeight - kToolbarHeight) {
      if (!_showTitle) setState(() => _showTitle = true);
    } else {
      if (_showTitle) setState(() => _showTitle = false);
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Widget _buildHeader() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: MyCachedNetworkImage(
            imageUrl: _info['coverImgUrl'],
            width: 120,
            height: 120,
            x: 480,
            y: 480,
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                _info['name'],
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              const SizedBox(height: 6),
              Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: MyCachedNetworkImage(
                      imageUrl: _info['avatarUrl'],
                      width: 18,
                      height: 18,
                      x: 96,
                      y: 96,
                    ),
                  ),
                  const SizedBox(width: 6),
                  Text(
                    _info['nickname'],
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                  ),
                  const SizedBox(width: 6),
                  Row(
                    children: List.generate(_info['tags'].length, (index) {
                      return Text(
                        '${_info['tags'][index]} ',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      );
                    }),
                  ),
                ],
              ),
              const SizedBox(height: 6),
              Text(
                _info['description'],
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 12,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildActions() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildCapsule(Icons.share, '99', () {}),
        _buildCapsule(Icons.comment, '88', () {}),
        _buildCapsule(Icons.add_box, '999', () {}),
      ],
    );
  }

  Widget _buildCapsule(IconData icon, String label, VoidCallback callback) {
    return GestureDetector(
      onTap: callback,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 34, vertical: 8),
        decoration: BoxDecoration(
          // 24%透明度
          color: Colors.white24,
          borderRadius: BorderRadius.circular(18),
        ),
        child: Row(
          children: [
            Icon(
              icon,
              size: 16,
              color: Colors.white,
            ),
            const SizedBox(width: 4),
            Text(
              label,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPlayAll() {
    return SizedBox(
      height: 56,
      child: DecoratedBox(
        decoration: const BoxDecoration(
          color: Colors.black,
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.zero,
          child: Container(
            height: 56,
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            child: Row(
              children: [
                IconButton(
                  onPressed: () {},
                  icon: const Icon(
                    Icons.play_circle_fill,
                    color: Color(0xFFf43f3b),
                    size: 24,
                  ),
                ),
                const SizedBox(width: 8),
                const Text(
                  '播放全部',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () {},
                  icon: const Icon(
                    Icons.add,
                    size: 24,
                    color: Colors.black,
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSongItem(Map<String, dynamic> song) {
    // 音乐播放控制方法
    final audioController = Get.find<AudioPlayerController>();
    return ListSongItem(
      id: song['id'],
      fee: song['fee'],
      imageUrl: song['al']['picUrl'],
      title: song['name'],
      artist: (song['ar'] as List)
          .map(
            (artist) => artist['name'],
          )
          .join(', '),
      onTap: () {
        audioController.playSong(song);
        audioController.setPlayList(_info['songlist']);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _info['songlist'] == null
          ? const Center(
              child: CircularProgressIndicator(
              backgroundColor: Color(0xFFf43f3b),
              color: Color(0xFFffffff),
            ))
          : NestedScrollView(
              controller: _scrollController,
              headerSliverBuilder: (context, innerBoxIsScrolled) => [
                SliverAppBar(
                  pinned: true,
                  expandedHeight: _headerHeight,
                  flexibleSpace: FlexibleSpaceBar(
                    background: GestureDetector(
                      onTap: () {
                        showModalBottomSheet(
                          context: context,
                          backgroundColor: Colors.transparent,
                          isScrollControlled: true,
                          builder: (_) => PlayListInfoDetail(
                            name: _info['name'],
                            tags: _info['tags'].toList(),
                            description: _info['description'],
                            imageUrl: _info['coverImgUrl'],
                          ),
                        );
                      },
                      child: Stack(
                        fit: StackFit.expand, // 设置除了定位组件外的组件为满屏 测试效果 设置了宽高也会满屏
                        children: [
                          MyCachedNetworkImage(
                            imageUrl: _info['songlist'][0]['al']['picUrl'],
                            width: 120,
                            height: 120,
                            x: 480,
                            y: 480,
                          ),
                          // 高斯模糊效果
                          BackdropFilter(
                            filter:
                                ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
                            child:
                                Container(color: Colors.black.withOpacity(0.7)),
                          ),
                          Positioned(
                            top: 100,
                            left: 16,
                            right: 16,
                            child: _buildHeader(),
                          ),
                          Positioned(
                            bottom: 10,
                            left: 16,
                            right: 16,
                            child: _buildActions(),
                          ),
                        ],
                      ),
                    ),
                  ),
                  leading: IconButton(
                    icon: const Icon(Icons.chevron_left_rounded),
                    onPressed: () => Get.back(),
                  ),
                  actions: [
                    IconButton(
                      onPressed: () {},
                      icon: const Icon(Icons.search),
                    ),
                    IconButton(
                      onPressed: () {},
                      icon: const Icon(Icons.more_vert),
                    ),
                  ],
                  title: _showTitle
                      ? SizedBox(
                          width: 250,
                          child: Text(
                            _info['name'],
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        )
                      : null,
                ),
                SliverPersistentHeader(
                  pinned: true,
                  delegate: _SliverPlayAllHeader(
                    height: 56,
                    child: _buildPlayAll(),
                  ),
                ),
              ],
              body: ListView.builder(
                // 作用：移除 ListView 的默认内边距，让内容贴紧边界。
                padding: EdgeInsets.zero,
                itemCount: _info['songlist'].length,
                itemBuilder: (context, index) {
                  return _buildSongItem(_info['songlist'][index]);
                },
              ),
            ),
    );
  }
}

class _SliverPlayAllHeader extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double height;

  _SliverPlayAllHeader({
    required this.child,
    this.height = 56,
  });

  @override
  double get minExtent => height;

  @override
  double get maxExtent => height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  bool shouldRebuild(covariant _SliverPlayAllHeader oldDelegate) {
    return oldDelegate.child != child || oldDelegate.height != height;
  }
}
